from loguru import logger
from datetime import datetime,timedelta
from tornado.limit import Tornado


blockTornado = Tornado("block", 3 , 10 * 60)

def handle_error_code(errors):
    for error in errors:
        for (key,value) in error.items():
            # logger.error(f"key:{key},value={value}")
            check_error(key,value)


def handle_warning_code(warnings):
    for warning in warnings:
        for key,value in warning.items():
            logger.warning(f"key:{key},value={value}")

send_flag = False

def check_error(key,value):
    global send_flag
    if key in ["52200"]:
        timestamp = datetime.now().timestamp()
        delta = timedelta( seconds= timestamp - value)
        minutes, seconds = divmod(delta.seconds, 60)
        time_str = f"AGV被独挡，超时{minutes:02d}:{seconds:02d}"
        if minutes > 15:
            if not send_flag:
                blockTornado.send("AGV被阻挡超过15min，请值班查看原因")
                logger.warning("AGV被阻挡超过15min，请值班查看原因")
                send_flag = True
